from flask_socketio import SocketIO
from eventlet.semaphore import Semaphore
from collections import defaultdict

class SessionInfo:

    
    def __init__(self, id:str, ws:SocketIO, sid:str, full_url:str):
        self.id = id
        self.flow_prev_nodes_executed_number = {} # {node_id: {prev_node_id: executed_number}}  当某一个node_id 的所有prev_node_id的值均相同，则执行node_id
        self.ws = ws
        self.sid = sid
        self.full_url = full_url
        # Register this session
        self.exe_historys = []
        self.out = {} # nodeID:{handle:[outputs]}
        self.out_write_lock = Semaphore()

    def clear(self):
        with self.out_write_lock:
            self.out.clear()

    def __del__(self):
        pass
    
    def add_new_exe_his(self, exe_his):
        self.exe_historys.append(exe_his)

    def get_newest_exe_his(self, num=1):
        if (len(self.exe_historys)<num):return self.exe_historys
        return self.exe_historys[-num:]

    def update_exe_his_order(self, exe_his):
        if exe_his in self.exe_historys:
            self.exe_historys.remove(exe_his)
            self.exe_historys.append(exe_his)

    def done_exe_with_nodeID(self, nodeID):
        i=-1
        while(1 <= -i <= len(self.exe_historys)):
            if self.exe_historys[i].nodeID==nodeID:
                self.exe_historys[i].done()
                break
            i-=1
